package com.cb.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cb.eduservice.entity.EduSubject;
import com.cb.eduservice.entity.excel.SubjectData;
import com.cb.eduservice.service.EduSubjectService;
import com.cb.servicebase.exception.GuliException;

/**
 * 课程管理 - 读取Excel - 监听器
 *
 * @author cb
 * @version 1.0
 * @date 2020/6/22 15:59
 */
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {
    /**
     * {@code SubjectExcelListener}无法直接交给 Spring 管理
     * 所以需要手动传入一个{@code EduSubjectService} 来方便我们
     * 进行数据库的操作.
     */
    public EduSubjectService subjectService;

    public SubjectExcelListener() {
    }

    public SubjectExcelListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        // 上传的文件数据为空
        if (subjectData == null) {
            throw new GuliException(20001, "文件数据为空");
        }
        // 判断数据库中是否已经存在当前行的数据
        EduSubject one = this.existOneSubject(subjectData.getOneSubjectName());
        if (one == null) {
            // 没有相同数据, 存入数据库
            one = new EduSubject();
            one.setParentId("0");
            one.setTitle(subjectData.getOneSubjectName());
            subjectService.save(one);
        }

        // 二级分类
        String parentId = one.getId();
        EduSubject two = this.existTwoSubject(subjectData.getTwoSubjectName(), "");
        if (two == null) {
            // 没有相同数据, 存入数据库
            two = new EduSubject();
            two.setParentId(parentId);
            two.setTitle(subjectData.getTwoSubjectName());
            subjectService.save(two);
        }

    }
    /**
     * 判断一级分类不能重复添加
     */
    private EduSubject existOneSubject(String name){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", 0);
        return subjectService.getOne(wrapper);
    }

    /**
     * 判断二级分类不能重复添加
     */
    private EduSubject existTwoSubject(String name,String parentId){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", parentId);
        return subjectService.getOne(wrapper);
    }
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
